package com.vmix.android.vmixsdk.rds;

import java.util.ArrayList;

import com.vmix.android.vmixsdk.exception.VmixException;

import android.app.Service;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.os.Bundle;
import android.os.IBinder;

public class PlayVideoService extends Service {

	public static final String PLAY_URL_FOUND = "play_url_found";
	
	protected PlayVideoOperation operation = null;
	protected String playToken = "";
	private String playUrl = "";

	private Thread thread = null;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Bundle bundle = intent.getExtras();
		this.playToken = bundle.getString("playToken");
		
		this.thread = new Thread( null, this.doBackgroundThreadProcessing, "playVideoOperationThread");
		
		// start the thread
		this.thread.start();

		return Service.START_STICKY;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
	
		super.onDestroy();
		
		this.stopThreads();
	}
	
	/**
	 * return the private playUrl
	 * @return
	 */
	public String getPlayUrl() {
		
		return this.playUrl;
		
	}
	
	/**
	 * get the play url
	 */
	private void performPlayVideo() {
		
		try {
			this.operation = new PlayVideoOperation( this.playToken );
			
			this.playUrl = this.operation.process();
			
			if( this.playUrl.length() > 0 ) {
				
				this.onLoadComplete();
				
			}
			
		}
		catch( VmixException e ) {
			
			// TODO
		}
	}
	
	// define background runnable
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
			
			performPlayVideo();
		
		}
	};
	
	
	/**
	 * announce load complete for anyone who listens
	 */
	private void onLoadComplete() {
	
		// stopping thrads
		// this.stopThreads();
		
		// create new intent
		Intent intent = new Intent( PlayVideoService.PLAY_URL_FOUND );
		// add extra info
		intent.putExtra("playUrl",  this.playUrl);
		
		// broadcast
		sendBroadcast( intent );
	}
	
	// stopping all the running threads
	private void stopThreads() {
		
		// stopping
		if( this.thread.isAlive() ) {
		
			this.thread.stop();
		}
	}
}
